<template>
  <div class="image-info">
    <div class="choose-container">
      <div class="choose" @click="chooseFile">请选择您要上传的图片
        <input id="avatar" type="file" style="display: none;" accept="image/*" @change="cropAvatar"/>
      </div>
    </div>
    <div class="upload-container">
      <div class="left">
        <div class="img-container">
          <div class="block">
            <span class="type">仅支持JPG、GIF、PNG、JPEG、BMP格式，文件小于3M</span>
            <el-image :src="url" />
          </div>
          <el-dialog
            :title="title"
            :visible.sync="open"
            width="800px"
            append-to-body
            @opened="modalOpened"
          >
            <el-row>
              <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                <vue-cropper
                  v-if="visible"
                  ref="cropper"
                  :img="options.img"
                  :info="true"
                  :auto-crop="options.autoCrop"
                  :auto-crop-width="options.autoCropWidth"
                  :auto-crop-height="options.autoCropHeight"
                  @realTime="realTime"
                />
              </el-col>
              <!-- 这里是实时预览有些毛病,还没调试完 -->
              <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                <div class="avatar-upload-preview">
                  <img :src="previews.url" :style="previews.img">
                </div>
              </el-col>
<!--              <el-col :xs="24" :md="12" :style="{ height: '350px' }">-->
<!--                <div v-html="previews.html" />-->
<!--              </el-col>-->
            </el-row>
            <br>
            <el-row>
              <el-col :lg="2" :md="2">
                <el-button size="small" @click="chooseFile">
                  重新选择
                  <i class="el-icon-upload el-icon--right" />
                </el-button>
              </el-col>
              <br>
              <el-col :lg="{ span: 1, offset: 2 }" :md="2">
                <el-button
                  icon="el-icon-plus"
                  size="small"
                  @click="changeScale(1)"
                />
              </el-col>
              <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                <el-button
                  icon="el-icon-minus"
                  size="small"
                  @click="changeScale(-1)"
                />
              </el-col>
              <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                <el-button
                  icon="el-icon-refresh-left"
                  size="small"
                  @click="rotateLeft"
                />
              </el-col>
              <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                <el-button
                  icon="el-icon-refresh-right"
                  size="small"
                  @click="rotateRight"
                />
              </el-col>
              <el-col :lg="{ span: 2, offset: 6 }" :md="2">
                <el-button
                  type="primary"
                  size="small"
                  :loading="disabled"
                  @click="uploadImg"
                  v-text="disabled ? '上传中' : '保 存'"
                >保 存</el-button>
              </el-col>
            </el-row>
          </el-dialog>
        </div>
      </div>
      <div class="right">
        <div>效果预览</div>
        <div class="txt">
          你上传的图片会自动生成2种尺寸，请注意
          <br>小尺寸的头像是否清晰
        </div>
        <div class="img-big">
          <img :src="url" alt>
        </div>
        <div class="size">100*100像素</div>
        <div class="img-small">
          <img :src="url" alt>
        </div>
        <div class="size">50*50像素</div>
      </div>
    </div>
<!--    <div class="submit">提交</div>-->
  </div>
</template>

<script>
import { changeAvatar } from '@/api/personal-center'
export default {
  data() {
    return {
      url: this.$store.getters.avatar || require('../../../assets/images/head-portrait.png'),
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '修改头像',
      fileName: '',
      // 是否显示cropper
      visible: false,
      disabled: false,
      options: {
        img: undefined, // 裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 300, // 默认生成截图框宽度
        autoCropHeight: 300 // 默认生成截图框高度
      },
      previews: {}
    }
  },
  methods: {
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    chooseFile() {
      document.getElementById('avatar').click()
    },
    // 裁剪
    cropAvatar($event) {
      const file = $event.target.files[0]
      const isLt3M = file.size / 1024 / 1024 < 3
      if (file.type.indexOf('image/') === -1) {
        this.$message('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
        file.value = ''
      } else if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.options.img = reader.result
          this.fileName = file.name
          this.open = true
          this.visible = true
        }
      }
    },
    // 构造文件流
    toBlob(dataURL) {
      const arr = dataURL.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bStr = atob(arr[1])
      let n = bStr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bStr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    // 上传图片
    uploadImg() {
      this.disabled = true
      this.$refs.cropper.getCropData(data => { // 获取截图的base64 数据
        const formData = new FormData()
        formData.append('image', this.toBlob(data), this.fileName)
        changeAvatar(formData).then(res => {
          this.url = data
          if (res.data) {
            this.$store.dispatch('setAvatar', data)
            const userInfo = JSON.parse(
              JSON.stringify(this.$store.getters.info)
            )
            userInfo.userAvar = data
            this.$store.dispatch('setInfoParam', userInfo)
            this.disabled = false
            this.visible = false
            this.open = false
            this.$message('修改成功')
          } else {
            this.disabled = false
            this.$message('修改失败')
          }
        }).catch(() => {
          this.disabled = false
          this.$message('请求失败')
        })
      })
      // this.$refs.cropper.getCropBlob(data => { // 获取截图的blob数据
      //   const formData = new FormData()
      //   formData.append('image', data, this.fileName)
      //   changeAvatar(formData).then(res => {
      //     if (res.data) {
      //       const reader = new FileReader()
      //       reader.readAsDataURL(data)
      //       reader.onload = e => {
      //         this.url = e.target.result
      //         this.$store.dispatch('setAvatar', this.url)
      //         const userInfo = JSON.parse(
      //           JSON.stringify(this.$store.getters.info)
      //         )
      //         userInfo.userAvar = this.url
      //         this.$store.dispatch('setInfoParam', userInfo)
      //       }
      //       this.disabled = false
      //       this.open = false
      //       this.visible = false
      //       this.$message('修改成功')
      //     } else {
      //       this.disabled = false
      //       this.$message('修改失败')
      //     }
      //   }).catch(() => {
      //     this.disabled = false
      //   })
      // })
    },
    // 实时预览
    realTime(data) {
      this.previews = data
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-row:last-child{
display: flex;
align-items: center;
}
::v-deep .el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: none;
  padding: 14px;
}
.image-info {
  padding: 50px 0 0 120px;
  .choose-container {
    .choose {
      width: 185px;
      height: 38px;
      background-color: #fc8a41;
      color: #fff;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .upload-container {
    display: flex;
    .left {
      margin-right: 125px;
.block{
  display: flex;
  flex-direction: column;
  position: relative;
  ::v-deep .el-icon-plus{
font-weight: 700;
font-size: 30px;
position: absolute;
color: #f8f8f8;
top: 50%;
left: 33%;
z-index: 100;
  }
  ::v-deep .el-image{
width: 251px;
 height: 251px;
 background-color: #F8F8F8FF;
 display: flex;
 justify-content: center;
 align-items: center;
}
::v-deep .el-image__inner{
width: 251px;
 height: 251px;
 object-fit: cover;
}
}
      .type {
        color: #8e8e93;
        font-size: 13px;
        margin: 6px 0 18px 0;
      }
      .show-img {
        width: 251px;
        height: 251px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f3f3f3ff;
        img {
          width: 93px;
          height: 112px;
          object-fit: cover;
        }
      }
    }
    .right {
      .txt {
        color: #8e8e93;
        font-size: 13px;
        margin: 16px 0;
      }
      .img-big {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #8e8e93;
        font-size: 13px;
        background-color: #f3f3f3ff;
        width: 100px;
        height: 100px;
        img {
           width: 100px;
        height: 100px;
          object-fit: cover;
        }
      }
      .size {
        height: 18px;
        margin: 5px 0 17px 0;
        color: #8e8e93ff;
      }
      .img-small {
        color: #8e8e93;
        font-size: 13px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f3f3f3ff;
        width: 50px;
        height: 50px;
        img {
           width: 50px;
        height: 50px;
          object-fit: cover;
        }
      }
    }
  }
  .submit {
    // margin-top: 20px;
    width: 110px;
    height: 37px;
    background-color: #ff3b30;
    font-size: 16px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
  }
}
</style>
